package com.itheima.java.ai.langchin4j.server.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.java.ai.langchin4j.entity.HealthRecord;
import com.itheima.java.ai.langchin4j.mapper.HealthRecordMapper;
import com.itheima.java.ai.langchin4j.server.HealthRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class HealthRecordServiceImpl extends ServiceImpl<HealthRecordMapper, HealthRecord> implements HealthRecordService {
    
    @Autowired
    private HealthRecordMapper healthRecordMapper;
    
    @Override
    public HealthRecord getByUserId(Long userId) {
        HealthRecord healthRecord = healthRecordMapper.findByUserId(userId);
        if (healthRecord == null) {
            // 如果不存在健康档案，则初始化一个
            healthRecord = initHealthRecord(userId);
        }
        return healthRecord;
    }
    
    @Override
    public boolean saveOrUpdateHealthRecord(HealthRecord healthRecord) {
        HealthRecord existingRecord = healthRecordMapper.findByUserId(healthRecord.getUserId());
        
        if (existingRecord != null) {
            // 更新现有记录
            healthRecord.setId(existingRecord.getId());
            healthRecord.setCreatedAt(existingRecord.getCreatedAt());
            healthRecord.setUpdatedAt(LocalDateTime.now());
            return updateById(healthRecord);
        } else {
            // 创建新记录
            healthRecord.setCreatedAt(LocalDateTime.now());
            healthRecord.setUpdatedAt(LocalDateTime.now());
            return save(healthRecord);
        }
    }
    
    @Override
    public HealthRecord initHealthRecord(Long userId) {
        // 先检查是否已存在健康档案
        HealthRecord existingRecord = healthRecordMapper.findByUserId(userId);
        if (existingRecord != null) {
            return existingRecord;
        }
        
        HealthRecord healthRecord = new HealthRecord();
        healthRecord.setUserId(userId);
        healthRecord.setAllergies("");
        healthRecord.setMedicalHistory("");
        healthRecord.setFamilyHistory("");
        healthRecord.setCurrentMedications("");
        healthRecord.setCreatedAt(LocalDateTime.now());
        healthRecord.setUpdatedAt(LocalDateTime.now());
        
        // 确保userId不为null
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 使用mapper直接插入，确保userId字段被包含
        int result = healthRecordMapper.insert(healthRecord);
        if (result <= 0) {
            throw new RuntimeException("初始化健康档案失败");
        }
        
        return healthRecord;
    }
}